<?php
/**
 * Created by PhpStorm.
 * Author: 芸签cms www.yunqiancms.com
 * User: sun
 * Date: 2022/6/29
 * Time: 9:55 AM
 */
namespace app\common\routes;

use Illuminate\Support\Str;
class CmsRouteDirector
{
    public $route;
    public $routes;
    public function __construct(ICmsRoute $route)
    {
        $this->route = $route;
        $this->routes = request()->input('route');
    }

    public function setRoute()
    {
        list($class_name,$action) = $this->match();
        request()->setRoute($this->routes);
        $routes = app('routes')->getRoutesByMethod();
        $current_route = $routes[request()->method()][$this->route->path];
        $current_route->action['uses'] = $class_name.'@'.$action;
        $current_route->action['controller'] = $class_name.'@'.$action;
        $current_route->action['namespace'] = $class_name;
        //中间件
        $middleware = $this->route->getMiddleware();
        $current_route->action['middleware'] = array_merge($current_route->action['middleware'],$middleware);
        return true;
    }

    private function match()
    {
        $routes = explode('.', $this->routes);
        $first = array_shift($routes);
        if ($first == 'plugin') {
            //插件路由
            $route = $this->route->pluginMatch($routes,$first);
        } else {
            //系统路由
            $route = $this->route->routeMatch($routes,$first);
        }
        list($classname,$action) = $route;
        if (empty($action)) {
            $action = $action ?: 'index';
            $this->routes .=  '.index';
        }
        $action = strpos($action, '-') === false ? $action : Str::camel($action);
        return [$classname,$action];

    }
}